<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义右键菜单</title>
    <style>
        body {
            font-size: 16px;
            font-family: "KaiTi";
        }
        * {
            padding: 0;
            margin: 0;
        }
        ul {
            list-style: none;
        }
        a {
            text-decoration: none;
            color: #333;
        }
        .contextmenu {
            width: 200px;
            border: 1px solid #999;
            box-shadow: 3px 3px 3px #ccc;
            background-color: #fff;
            position: absolute;
            top: 10px;
            left: 10px;
            display: none;
        }
        .contextmenu li {
            height: 40px;
            line-height: 40px;
        }
        .contextmenu li a {
            display: block;
            padding: 0 30px;
        }
        .contextmenu li a:hover {
            background-color: #ccc;
            font-weight: bold;
            color: #fff;
        }
    </style>
</head>
<body>

<div class="contextmenu" id="context">
    <ul>
        <li><a href="javascript:;">复制</a></li>
        <li><a href="javascript:;">粘贴</a> </li>
        <li><a href="javascript:;">剪切</a></li>
        <li><a href="javascript:;">下载</a></li>
        <li><a href="javascript:;">上传</a></li>
    </ul>
</div>

</body>
<script>

    document.oncontextmenu = function(env){

        //env 表示event事件
        // 兼容event事件写法
        var e = env || window.event;

        // 获取菜单，让菜单显示出来
        var context = document.getElementById("context");
        context.style.display = "block";

        //  让菜单随着鼠标的移动而移动
        //  获取鼠标的坐标
        var x = e.clientX;
        var y = e.clientY;

        //  获取窗口的宽度和高度
        var w = window.innerWidth;
        var h = window.innerHeight;

        //  调整宽度和高度
        context.style.left = Math.min(w-202,x)+"px";
        context.style.top = Math.min(h-230,y)+"px";

        // return false可以关闭系统默认菜单
        return false;
    };

    //   当鼠标点击后关闭右键菜单
    document.onclick = function(){
        var contextmenu = document.getElementById("context");
        contextmenu.style.display = "none";

    };

</script>
</html>